using Senparc.Weixin.Entities;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.HttpUtility;
using Senparc.Weixin.QY.Entities;
using Senparc.Weixin.QY.Entities.Menu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace Senparc.Weixin.QY.CommonAPIs
{
	public class CommonApi
	{
		public const string API_URL = "https://qyapi.weixin.qq.com/cgi-bin";
		public static AccessTokenResult GetToken(string corpId, string corpSecret)
		{
			string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpId, corpSecret);
			return Get.GetJson<AccessTokenResult>(url, null);
		}
		public static GetCallBackIpResult GetCallBackIp(string accessToken)
		{
			string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/getcallbackip?access_token={0}", accessToken);
			return Get.GetJson<GetCallBackIpResult>(url, null);
		}
		public static JsApiTicketResult GetTicket(string corpId, string corpSecret)
		{
			string access_token = CommonApi.GetToken(corpId, corpSecret).access_token;
			string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/jsapi_ticket?access_token={0}", access_token);
			return Get.GetJson<JsApiTicketResult>(url, null);
		}
		public static ProviderTokenResult GetProviderToken(string corpId, string providerSecret, int timeOut = 10000)
		{
			string urlFormat = "https://qyapi.weixin.qq.com/cgi-bin/service/provider_token";
			var data = new
			{
				corpid = corpId,
				provider_secret = providerSecret
			};
			return CommonJsonSend.Send<ProviderTokenResult>(null, urlFormat, data, CommonJsonSendType.POST, timeOut);
		}
		public static ConvertToOpenIdResult ConvertToOpenId(string accessToken, string userId, string agentId = null, int timeOut = 10000)
		{
			string urlFormat = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token={0}", accessToken);
			var data = new
			{
				userid = userId,
				agentid = agentId
			};
			return CommonJsonSend.Send<ConvertToOpenIdResult>(null, urlFormat, data, CommonJsonSendType.POST, timeOut);
		}
		public static ConvertToUserIdResult ConvertToUserId(string accessToken, string openId, int timeOut = 10000)
		{
			string urlFormat = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token={0}", accessToken);
			var data = new
			{
				openid = openId
			};
			return CommonJsonSend.Send<ConvertToUserIdResult>(null, urlFormat, data, CommonJsonSendType.POST, timeOut);
		}
		public static QyJsonResult CreateMenu(string accessToken, int agentId, ButtonGroup buttonData, int timeOut = 10000)
		{
			string urlFormat = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token={0}&agentid={1}", accessToken, agentId);
			return CommonJsonSend.Send(null, urlFormat, buttonData, CommonJsonSendType.POST, timeOut);
		}
		[Obsolete("配合GetMenuFromJson方法使用")]
		private static SingleClickButton GetSingleButtonFromJsonObject(Dictionary<string, object> objs)
		{
			return new SingleClickButton
			{
				key = objs["key"] as string,
				name = objs["name"] as string,
				type = objs["type"] as string
			};
		}
		[Obsolete("此方法通过判断GetMenuResult并结合object类型转换得到结果。结果准确。但更推荐使用GetMenuFromJsonResult方法。")]
		public static GetMenuResult GetMenuFromJson(string jsonString)
		{
			GetMenuResult getMenuResult = new GetMenuResult();
			try
			{
				JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
				object obj = javaScriptSerializer.Deserialize<object>(jsonString);
				Dictionary<string, object> dictionary = obj as Dictionary<string, object>;
				if (dictionary != null && dictionary.ContainsKey("menu"))
				{
					object obj2 = dictionary["menu"];
					object[] array = (obj2 as Dictionary<string, object>)["button"] as object[];
					object[] array2 = array;
					for (int i = 0; i < array2.Length; i++)
					{
						object obj3 = array2[i];
						Dictionary<string, object> dictionary2 = obj3 as Dictionary<string, object>;
						if (dictionary2.ContainsKey("key") && !string.IsNullOrEmpty(dictionary2["key"] as string))
						{
							getMenuResult.menu.button.Add(CommonApi.GetSingleButtonFromJsonObject(dictionary2));
						}
						else
						{
							SubButton subButton = new SubButton(dictionary2["name"] as string);
							getMenuResult.menu.button.Add(subButton);
							object[] array3 = dictionary2["sub_button"] as object[];
							for (int j = 0; j < array3.Length; j++)
							{
								object obj4 = array3[j];
								subButton.sub_button.Add(CommonApi.GetSingleButtonFromJsonObject(obj4 as Dictionary<string, object>));
							}
						}
					}
				}
				else
				{
					if (dictionary != null && dictionary.ContainsKey("errmsg"))
					{
						throw new ErrorJsonResultException(dictionary["errmsg"] as string, null, null);
					}
				}
			}
			catch (ErrorJsonResultException)
			{
				getMenuResult = null;
			}
			catch (Exception)
			{
				getMenuResult = null;
			}
			return getMenuResult;
		}
		public static GetMenuResult GetMenu(string accessToken, int agentId)
		{
			string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token={0}&agentid={1}", accessToken, agentId);
			string input = RequestUtility.HttpGet(url, Encoding.UTF8);
			JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
			GetMenuResult result;
			try
			{
				GetMenuResultFull getMenuResultFull = javaScriptSerializer.Deserialize<GetMenuResultFull>(input);
				if (getMenuResultFull.menu == null || getMenuResultFull.menu.button.Count == 0)
				{
					throw new WeixinException(getMenuResultFull.errmsg);
				}
				result = CommonApi.GetMenuFromJsonResult(getMenuResultFull);
			}
			catch (WeixinException)
			{
				result = null;
			}
			return result;
		}
		public static GetMenuResult GetMenuFromJsonResult(GetMenuResultFull resultFull)
		{
			GetMenuResult result = null;
			try
			{
				ButtonGroup buttonGroup = new ButtonGroup();
				foreach (MenuFull_RootButton current in resultFull.menu.button)
				{
					if (current.name != null)
					{
						if (current.sub_button.Count((MenuFull_RootButton z) => !string.IsNullOrEmpty(z.name)) == 0)
						{
							if (current.type == null || (current.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(current.key)))
							{
								throw new WeixinMenuException("单击按钮的key不能为空！");
							}
							if (current.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase))
							{
								buttonGroup.button.Add(new SingleClickButton
								{
									name = current.name,
									key = current.key,
									type = current.type
								});
							}
							else
							{
								if (current.type.Equals("VIEW", StringComparison.OrdinalIgnoreCase))
								{
									buttonGroup.button.Add(new SingleViewButton
									{
										name = current.name,
										url = current.url,
										type = current.type
									});
								}
								else
								{
									if (current.type.Equals("LOCATION_SELECT", StringComparison.OrdinalIgnoreCase))
									{
										buttonGroup.button.Add(new SingleLocationSelectButton
										{
											name = current.name,
											key = current.key,
											type = current.type
										});
									}
									else
									{
										if (current.type.Equals("PIC_PHOTO_OR_ALBUM", StringComparison.OrdinalIgnoreCase))
										{
											buttonGroup.button.Add(new SinglePicPhotoOrAlbumButton
											{
												name = current.name,
												key = current.key,
												type = current.type
											});
										}
										else
										{
											if (current.type.Equals("PIC_SYSPHOTO", StringComparison.OrdinalIgnoreCase))
											{
												buttonGroup.button.Add(new SinglePicSysphotoButton
												{
													name = current.name,
													key = current.key,
													type = current.type
												});
											}
											else
											{
												if (current.type.Equals("PIC_WEIXIN", StringComparison.OrdinalIgnoreCase))
												{
													buttonGroup.button.Add(new SinglePicWeixinButton
													{
														name = current.name,
														key = current.key,
														type = current.type
													});
												}
												else
												{
													if (current.type.Equals("SCANCODE_PUSH", StringComparison.OrdinalIgnoreCase))
													{
														buttonGroup.button.Add(new SingleScancodePushButton
														{
															name = current.name,
															key = current.key,
															type = current.type
														});
													}
													else
													{
														buttonGroup.button.Add(new SingleScancodeWaitmsgButton
														{
															name = current.name,
															key = current.key,
															type = current.type
														});
													}
												}
											}
										}
									}
								}
							}
						}
						else
						{
							SubButton subButton = new SubButton(current.name);
							buttonGroup.button.Add(subButton);
							foreach (MenuFull_RootButton current2 in current.sub_button)
							{
								if (current2.name != null)
								{
									if (current2.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase) && string.IsNullOrEmpty(current2.key))
									{
										throw new WeixinMenuException("单击按钮的key不能为空！");
									}
									if (current2.type.Equals("CLICK", StringComparison.OrdinalIgnoreCase))
									{
										subButton.sub_button.Add(new SingleClickButton
										{
											name = current2.name,
											key = current2.key,
											type = current2.type
										});
									}
									else
									{
										if (current2.type.Equals("VIEW", StringComparison.OrdinalIgnoreCase))
										{
											subButton.sub_button.Add(new SingleViewButton
											{
												name = current2.name,
												url = current2.url,
												type = current2.type
											});
										}
										else
										{
											if (current2.type.Equals("LOCATION_SELECT", StringComparison.OrdinalIgnoreCase))
											{
												subButton.sub_button.Add(new SingleLocationSelectButton
												{
													name = current2.name,
													key = current2.key,
													type = current2.type
												});
											}
											else
											{
												if (current2.type.Equals("PIC_PHOTO_OR_ALBUM", StringComparison.OrdinalIgnoreCase))
												{
													subButton.sub_button.Add(new SinglePicPhotoOrAlbumButton
													{
														name = current2.name,
														key = current2.key,
														type = current2.type
													});
												}
												else
												{
													if (current2.type.Equals("PIC_SYSPHOTO", StringComparison.OrdinalIgnoreCase))
													{
														subButton.sub_button.Add(new SinglePicSysphotoButton
														{
															name = current2.name,
															key = current2.key,
															type = current2.type
														});
													}
													else
													{
														if (current2.type.Equals("PIC_WEIXIN", StringComparison.OrdinalIgnoreCase))
														{
															subButton.sub_button.Add(new SinglePicWeixinButton
															{
																name = current2.name,
																key = current2.key,
																type = current2.type
															});
														}
														else
														{
															if (current2.type.Equals("SCANCODE_PUSH", StringComparison.OrdinalIgnoreCase))
															{
																subButton.sub_button.Add(new SingleScancodePushButton
																{
																	name = current2.name,
																	key = current2.key,
																	type = current2.type
																});
															}
															else
															{
																subButton.sub_button.Add(new SingleScancodeWaitmsgButton
																{
																	name = current2.name,
																	key = current2.key,
																	type = current2.type
																});
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
				result = new GetMenuResult
				{
					menu = buttonGroup
				};
			}
			catch (Exception ex)
			{
				throw new WeixinMenuException(ex.Message, ex);
			}
			return result;
		}
		public static QyJsonResult DeleteMenu(string accessToken, int agentId)
		{
			string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token={0}&agentid={1}", accessToken, agentId);
			return Get.GetJson<QyJsonResult>(url, null);
		}
	}
}
